package deadlock;

/**
 * @author Brook
 * 必然死锁
 */
public class MustDeadLock implements Runnable{

    int flag = 1;

    static Object o1 = new Object();
    static Object o2 = new Object();

    public static void main(String[] args) {
        MustDeadLock mustDeadLock1 = new MustDeadLock();
        MustDeadLock mustDeadLock2 = new MustDeadLock();
        mustDeadLock1.flag = 1;
        mustDeadLock2.flag = 0;
        Thread thread1 = new Thread(mustDeadLock1);
        Thread thread2 = new Thread(mustDeadLock2);
        thread1.start();
        thread2.start();
    }
    @Override
    public void run() {
        System.out.println("flag:="+flag);
        if(flag == 1){
            synchronized (o1) {
                System.out.println(Thread.currentThread().getName()+"获取到o1");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println(Thread.currentThread().getName() + ":转账成功");
                }
            }
        }
        if(flag == 0) {
            synchronized (o2) {
                System.out.println(Thread.currentThread().getName()+"获取到o2");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    System.out.println(Thread.currentThread().getName() + ":转账成功");
                }
            }
        }
    }
}
